import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.swing.JOptionPane;

/*
 * CurrencyConverter.java : This class gets information from 
 * 			CurrencyConverterGUI and calls the Reader class. 
 * 			By giving URL to Reader class, this class gets currency amount from Reader class 
 *			 by decoding the HTML code and sends the result to CurrencyConverterGUI.
 * 
 * @Author : BilCIS
 */

public class CurrencyConverter
{
	// Variables declaration
	private String target;
	private double amount;
	private String base;
	private String result;
	// End of variables declaration
	
	public CurrencyConverter( String target )
	{
		base = "TRY";
		this.target = target;
		//for staff info
		//amount = getSalary();
	}
	
	public CurrencyConverter( String base, String target, double amount )
	{
		this.base = base;
		this.target = target;
		this.amount = amount;
	}
	
	// Calculates given amount in given currencies.
	public double calculate()
	{
		String html ="";
		Reader r;

		try 
		{
			r = new Reader("http://finance.yahoo.com/q?s=" + base + target + "=X");
			html = r.read();
		} 
		catch (KeyManagementException e) 
		{
			JOptionPane.showMessageDialog(null, "No internet Connection");
			e.printStackTrace();
		} 
		catch (NoSuchAlgorithmException e) 
		{
			JOptionPane.showMessageDialog(null, "No internet Connection");
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			JOptionPane.showMessageDialog(null, "No internet Connection");
			e.printStackTrace();
		}

		result = html.substring( html.indexOf ( "<span id=\"yfs_l10_" + base.toLowerCase() + target.toLowerCase() + "=x\">" ) + 28,
						html.indexOf( "</span></span>" , html.indexOf ( "<span id=\"yfs_l10_" + base.toLowerCase() + target.toLowerCase() + "=x\">" ) ));
		return amount * Double.parseDouble ( result );
	}
}